#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include <random>

std::mutex mtx;
bool packet_received = false;

// 模拟发送方
void sender(int &seq, std::default_random_engine &generator) {
    while(true) {
        std::unique_lock<std::mutex> lock(mtx);
        if(!packet_received) { // 若未收到确认则重发
            std::uniform_int_distribution<int> dist(1, 100);
            bool lost = dist(generator) <= 20; // 20%丢包率
            
            if (!lost) {
                std::cout << "Sender: Packet " << seq << " sent.\n";
                packet_received = true;
            } else {
                std::cout << "Sender: Packet " << seq << " lost.\n";
            }
        }
        lock.unlock();
        std::this_thread::sleep_for(std::chrono::milliseconds(500)); // 等待
    }
}

// 模拟接收方
void receiver(int &seq) {
    while(true) {
        std::unique_lock<std::mutex> lock(mtx);
        if(packet_received) {
            std::cout << "Receiver: Ack for packet " << seq << " sent.\n";
            packet_received = false; // 发送确认后准备接收下个包
            seq = 1 - seq; // 切换序列号
        }
        lock.unlock();
        std::this_thread::sleep_for(std::chrono::milliseconds(500)); // 等待
    }
}

int main() {
    int seq = 0; // 序列号
    std::default_random_engine generator(std::random_device{}());
    
    std::thread t1(sender, std::ref(seq), std::ref(generator));
    std::thread t2(receiver, std::ref(seq));
    
    t1.join();
    t2.join();
    
    return 0;
}